;
cmedit.DownloadSystem = (function($, window, document) {
    var thisContext;
    var startPage = 1;
    var topUtil; //顶层工具类
    var loadTimeout = cmedit.global.loadTimeout;
    var tenantId = window.localStorage.getItem("tenantId");
    var userId = window.localStorage.getItem("userId");
    var token = window.localStorage.getItem("token");
    var DownloadSystemClass = function() {

    }
    DownloadSystemClass.prototype = {
        constructor: DownloadSystemClass,

        init: function() {
            thisContext = this;
            topUtil = window.parent.cmedit.global;
            thisContext.initViewStyle();
            thisContext.initData();
            thisContext.initEvent();
        },
        refresh : function(){
        	$('#downloadManageTable').bootstrapTable('refresh');
        },
        /**
         * 初始化页面视图
         */
        initViewStyle: function() {
            $('.re_contleft .slimScrollDiv').css('height', $(document).height() - 116 + 'px');
            $('.tab-content').css('height', $('.portlet-body').innerHeight() + 'px');
            //            $('.line-body').css('height',$('.cont_container').innerHeight()-203+'px');
            //
            //            /*修改滚动条样式*/
            //            var linescroll_height=$('.line-body').height();
            //            thisContext.scrollType('line-body',linescroll_height);

            $('#startTime').datepicker({ clearBtn: true, format: 'yyyy-mm-dd', autoclose: true });
            $('#endTime').datepicker({ clearBtn: true, format: 'yyyy-mm-dd', autoclose: true });
        },
        /**
         * 初始化数据
         */
        initData: function() {
            window.parent.cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
            thisContext.initDownloadStatus();
            thisContext.initDownloadPathSelect();
        },
        /**
         * 初始化事件
         */
        initEvent: function() {
            $('.nav-link').on('click', function() {
                $('.nav-link').removeClass('nav_active');
                $(this).addClass('nav_active');
            });
            $('.container_buttons button').on('click', function() {
                $(this).addClass('active').siblings().removeClass('active');
                thisContext.initDownloadStatus();
            });
            //重置刷新列表
            $('.download_refresh').on('click', function() {
                $('#searchContent').val('');
                $('#downloadPathSelect').val('');
                $("#downloadPathSelect").selectpicker('refresh');
                $(".container_buttons button[states='']").addClass('active').siblings().removeClass('active');
                $('.date-picker input').val('').datepicker('clearDates');

                //thisContext.initDownloadStatus();
            });
        },
        /**
         * 加载下载状态数据
         */
        initDownloadStatus: function(_currentPage,_pageSize) {
            //			$('#downloadManageBody').html(cmedit.global.loaderHtml);
            var $tableid = $('#downloadManageTable');
            var url = cmedit.global.cmsPath + "DownloadManageController/getDownloadManageByPage";
            var gc = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditDownload));
            var cmeditList = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditTypes));
            var hasCheckbox = true;
            if ($('#searchContent').val() != null &&
                $('#searchContent').val() != '') {
                var title = $('#searchContent').val();
            } else {
                var title = '';
            }
            var downloadPathGuid = $('#downloadPathSelect').val();
            var dateranges = '';
            //          if($('#endTime').val()!=null && $('#endTime').val()!=''){
            if (($('#endTime').val() != null && $('#endTime').val() != '') || ($('#startTime').val() != null && $('#startTime').val() != '')) {
                dateranges = $("#startTime").val() + " - " +
                    $("#endTime").val();
            } else {
                dateranges = '';
            }
            var currentPage = _currentPage ? _currentPage : 1;
            var pageSize =_pageSize ? _pageSize : 10;
            var states = $(".container_buttons button[class*='active']").attr(
                "states");
            var queryParams = {
                mainType: 0, // CMS稿
                mainHeader: title,
                dateranges: dateranges,
                downloadPathGuid: downloadPathGuid,
                downloadStatus: states,
                mbtStatus: states,
                currentPage:currentPage,
                pageSize:pageSize
            };
            var tableParams = {
                $tableid: $tableid,
                url: url,
                gc: gc,
                hasCheckbox: hasCheckbox,
                tenantId: tenantId,
                userId: userId,
                token: token,
                cmeditList: cmeditList,
                resourceType: "manuDownload",
                callBackLoadData:function(start,size){
                	thisContext.initDownloadStatus(start,size);
                }

            };
            console.log('tableParams:' + tableParams);
            TableInit(tableParams, queryParams);

            /*var datalist = {
		    	mainType : 0,// CMS稿
		    	mainHeader : title,
		    	dateranges : dateranges,
		    	downloadPathGuid : downloadPathGuid,
		    	downloadStatus : states,
				currentPage : page,
				mbtStatus : states,
				pageSize : '10',
			};
        	topUtil.ajaxRequest({
				type: "post",
				async: false,
				dataType: "json",
				url: cmedit.global.cmsPath+"DownloadManageController/getDownloadManageByPage",
				data: datalist,
				success: function(data) {
					if(data.status) {
						var templateData = {
							list : data.data.list,
						}
						var html=template('downloadManageList',templateData);
						if(html){
							setTimeout(function(){
								$('#downloadManageBody').html(html);
							},loadTimeout)
						}else{
							setTimeout(function(){
								$('#downloadManageBody').html("<span class='noResults'>暂无数据<span>");
							},loadTimeout)
						}
						$("#pagination").html('');
						thisContext.initPage(data.data.totalPage);
						if(!startPage){
							$('#pagination').whjPaging('setPage',1,data.data.totalPage);
						}
						console.log("列表刷新成功")
					}else{
						$.notify(data.msg);
						$('.manuLoader').hide();
						return false;
					}
				}
			});*/
        },
        /**
         * 初始化分页
         */
        initPage: function(totalPage) {
            $("#pagination").whjPaging({
                /*pageSizeOpt: [
                    {'value': 5, 'text': '5/page', 'selected': true},
                    {'value': 10, 'text': '10/page'},
                    {'value': 15, 'text': '15/page'},
                    {'value': 20, 'text': '20/page'}
                ],*/
                totalPage: totalPage,
                showPageNum: 4,
                firstPage: '<i class="iconfont icon-diyiye"></i>',
                previousPage: '<i class="iconfont icon-shangyiye"></i>',
                nextPage: '<i class="iconfont icon-xiayiye"></i>',
                lastPage: '<i class="iconfont icon-weiye"></i>',
                skip: 'skip',
                confirm: 'go',
                refresh: 'refresh',
                totalPageText: 'the total {} pages',
                isShowFL: true,
                isShowPageSizeOpt: false,
                isShowSkip: false,
                isShowRefresh: false,
                isShowTotalPage: false,
                isResetPage: true,
                callBack: function(currPage, pageSize) {
                    thisContext.initDownloadStatus(currPage);
                }
            });
        },

        /**
         *滚动条样式
         */
        scrollType: function(scrollId, scrollHeight) {
            $('.' + scrollId).slimScroll({
                height: scrollHeight, //可滚动区域高度
                size: '5px', //组件宽度
                color: '#999', //滚动条颜色
                railOpacity: .3, //滚动条透明度
                disableFadeOut: true, //鼠标经过可滚动区域时显示组件，离开时隐藏组件
                wheelStep: 20, //滚轮滚动量
                alwaysVisible: true, //始终显示组件
                borderRadius: '7px' //滚动条圆角
            });
        },
        /**
         * 渲染下载路径下拉列表
         * @param mainGuid
         */
        initDownloadPathSelect: function() {
            var postData = {
                mainType: 0, // CMS稿
                "currentPage": 1,
                "pageSize": 999
            };
            topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: cmedit.global.cmsPath + "DownloadManageController/getDownloadPathByPage",
                data: postData,
                success: function(data) {
                    if (data.status) {
                        $("#downloadPathSelect").html('<option value="">全部</option>');
                        var downloadPathList = data.data.list;
                        for (var i = 0; i < downloadPathList.length; i++) {
                            $("#downloadPathSelect").append('<option value="' + downloadPathList[i].downloadPathGuid + '">' + downloadPathList[i].downloadName + '</option>');
                        }
                        $("#downloadPathSelect").selectpicker('refresh');
                    }
                }
            });
        },


        /**
         *  重试下载
         * @param downloadStatusGuid
         * @param manuscriptMainGuid
         * @param downloadPathGuid
         * @param downloadType
         */
        downloadfileSpecifiedRetry: function(downloadStatusGuid, manuscriptMainGuid, downloadPathGuid, downloadType) {
            window.parent.cmedit.ManuscriptSystem.downloadfileSpecifiedRetry(downloadStatusGuid, manuscriptMainGuid, downloadPathGuid, downloadType);
        },

        /**
         * 删除记录
         * @param downloadStatusGuid
         */
        delResoure: function(downloadStatusGuid) {
            window.parent.cmedit.ManuscriptSystem.delDownlaodResoure(downloadStatusGuid);
        },
        /**
         * 显示下载失败原因
         * @param reason
         */
        showFailReason: function(obj, reason) {
            var thisObj = $(obj).parent().find('.popoverimg');
            var timer = null,
                popBox = thisObj.next(),
                imgtop = thisObj.offset().top,
                imgLeft = thisObj.position().left;
            var maxTop = $(window).height() - 240,
                theadTop = $('.fixed-table-header').offset().top + 155,
                boxWidth = $(".popover-box").outerWidth(),
                arrowWidth = $(".popover-arrow").outerWidth();
            var boxLeft = imgLeft - boxWidth * 0.85;
            console.log("imgtop:" + imgtop + " maxTop:" + maxTop + " theadTop:" + theadTop);
            thisObj.next().css('left', boxLeft + 'px');
            thisObj.next().find('.popover_content').html(reason);
            if (imgtop > maxTop && imgtop > theadTop) {
                popBox.addClass('popbox-transY');
                popBox.children('div:first-child').removeClass('popover-arrow-up').addClass('popover-arrow-down');

            } else {
                popBox.removeClass('popbox-transY');
                popBox.children('div:first-child').removeClass('popover-arrow-down').addClass('popover-arrow-up');
            }
            $(".popover-box").hide();
            popBox.show();
            thisObj.on("mouseout", function() {
                timer = setTimeout(function() {
                    popBox.hide();
                }, 500);
            });
            thisObj.prev().on("mouseout", function() {
                timer = setTimeout(function() {
                    popBox.hide();
                }, 500);
            });
            $(".popover-box").on("mouseover", function() {
                clearTimeout(timer);
                $(this).show();
            }).on("mouseout", function() {
                $(this).hide();
            });
        },

    };
    return new DownloadSystemClass();
})(jQuery, window, document);

$(cmedit.DownloadSystem.init());